package com.example.Less.controller;

import com.example.Less.entity.PageResponse;
import com.example.Less.entity.Photo;
import com.example.Less.entity.PhotoSearchQuery;
import com.example.Less. service.PhotoService;
import com.example.Less.util.MinioUtil;
import com.example.Less.util.ThumbnailUtil;
import io.micrometer.common.util.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/api/photos")
@RequiredArgsConstructor
public class PhotoController {
    
    private final PhotoService photoService;
    private final MinioUtil minioUtil;
    private final ThumbnailUtil thumbnailUtil;

    @PostMapping("/create")
    public ResponseEntity<Photo> createPhoto(@RequestBody Photo photo) {
        Photo savedPhoto = photoService.savePhoto(photo);
        return ResponseEntity.ok(savedPhoto);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Photo> getPhoto(@PathVariable Integer id) {
        Photo photo = photoService.getPhotoById(id);
        return ResponseEntity.ok(photo);
    }

    @GetMapping
    public ResponseEntity<List<Photo>> getAllPhotos() {
        List<Photo> photos = photoService.getAllPhotos();
        return ResponseEntity.ok(photos);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Photo> updatePhoto(@PathVariable Integer id, @RequestBody Photo photo) {
        photo.setId(id);
        Photo updatedPhoto = photoService.updatePhoto(photo);
        return ResponseEntity.ok(updatedPhoto);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deletePhoto(@PathVariable Integer id) {
        photoService.deletePhoto(id);
        return ResponseEntity.noContent().build();
    }
    @GetMapping("/search")
    public ResponseEntity<PageResponse<Photo> > searchPhotos(PhotoSearchQuery query) {

//        List<HashMap<String, String>> photos = photoService.searchPhotos(photoName, photoPath, type, projectId, isDeleted);
        PageResponse<Photo> response = photoService.searchPhotos(query);
        try {
            for (int i = 0; i < response.getList().size(); i++) {
                String photoNames = response.getList().get(i).getPhotoName();
                String photoPath = response.getList().get(i).getPhotoPath();
                if (StringUtils.isBlank(photoNames)) {
                    continue;
                }
                String fileUrl = minioUtil.getFileUrl(photoNames, 7);
                response.getList().get(i).setFileUrl(fileUrl);

                if (StringUtils.isBlank(photoPath)) {
                    continue;
                }
                String miniFileUrl = minioUtil.getFileUrl(photoPath, 7);
                response.getList().get(i).setMiniFileUrl(miniFileUrl);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


        return ResponseEntity.ok(response);
    }
    /**
     * 上传文件接口
     * @param file 上传的文件
     * @return 包含文件信息和访问路径的JSON
     */
    @PostMapping("/upload")
    public ResponseEntity<Map<String, String>> uploadFile(@RequestParam("file") MultipartFile file,Integer width,Integer height,Float quality) {
        Map<String, String> response = new HashMap<>();
        try {
            if (file.isEmpty()) {
                response.put("error", "Please select a file to upload.");
                return ResponseEntity.badRequest().body(response);
            }

            // 上传文件到MinIO
            String objectName = minioUtil.uploadFile(file);
            // 如果是图片文件，生成并上传缩略图
            if (thumbnailUtil.isImageFile(file)) {
                try {
                    if (width ==null || height == null || quality == null) {
                        width=500;
                        height=500;
                        quality = 1.0f;
                    }
                    byte[] thumbnailBytes = thumbnailUtil.generateThumbnail(file, width, height, quality);
                    String thumbnailObjectName = "thumbnails/" + thumbnailUtil.generateThumbnailFilename(
                            file.getOriginalFilename() != null ? file.getOriginalFilename() : "image.jpg");
                    String thumbnailUrl = minioUtil.uploadThumbnail(thumbnailBytes, thumbnailObjectName, file.getContentType());
                    String miniFileUrl = minioUtil.getFileUrl(thumbnailUrl, 7);
                    response.put("miniFileUrl", miniFileUrl);
                    response.put("miniFileName", thumbnailUrl);
                } catch (Exception e){

                }
            }
            // 获取文件的临时访问URL（例如有效期7小时）
            String fileUrl = minioUtil.getFileUrl(objectName, 7);

            // 构建返回结果
            response.put("message", "File uploaded successfully!");
            response.put("originalFilename", file.getOriginalFilename());
            response.put("objectName", objectName);
            response.put("fileUrl", fileUrl);
            response.put("contentType", file.getContentType());
            response.put("size", String.valueOf(file.getSize()));

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            e.printStackTrace();
            response.put("error", "File upload failed: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

}